package org.tc.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.tc.common.Result;
import org.tc.common.ResultUtils;
import org.tc.service.JedisService;
import org.tc.utils.HttpClientUtil;
import org.tc.utils.JsonUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zxd on 2018/1/31.
 */
@RequestMapping("/sms")
@Controller
public class SmsController {

    private Logger LOGGER= LoggerFactory.getLogger(SmsController.class);

    private final static String URL="http://106.ihuyi.com/webservice/sms.php?method=Submit";

    @Autowired
    private JedisService jedisService;

    @RequestMapping("/login/{phone}")
    public ResponseEntity<Result> sendSms(@PathVariable("phone") String phone){
        LOGGER.info("发送短信的电话号码是{}",phone);
        Map map=new HashMap();
        map.put("account","C04748990");
        map.put("password","810d4b3e92bb31a3ac0ef85f69db7adb");
        map.put("mobile",phone);
        int mobile_code = (int)((Math.random()*9+1)*100000);
        String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
        map.put("content",content);
        map.put("format","json");

        //服务器上存储验证码
        jedisService.set("login_sms:"+phone,mobile_code+"");
        jedisService.expire("login_sms:"+phone,30*60);

        //放松短信
        String json= HttpClientUtil.doGet(URL,map);
        if(!StringUtils.isEmpty(json)){
            Map result = JsonUtils.jsonToPojo(json, Map.class);
                    if(result.get("code").toString().equals("2")){
                        return ResponseEntity.ok(ResultUtils.buildSuccess());
                    }
        }
        return ResponseEntity.ok(ResultUtils.buildFail(107,"短信发送失败!"));
    }




}
